const http = require('http.js');

class Token {
    constructor() {
        
    }

    verify(callBack) {
        var token = wx.getStorageSync('token');
        console.log('TOKEN:' + token);
        if (!token) {
            this._getTokenFromServer(callBack);
        }
        else {
            this._veirfyFromServer(token, callBack);
        }
    }

    _veirfyFromServer(token, callBack) {
        var that = this;
        // 发送请求验证 token
        http.post('api/token/check').then(res => {
            console.log(res);
            if (res.code === 1) {
                if (res.data.token) {
                    console.log('Token 有效');
                    wx.setStorageSync('token_time', res.data.expires_in)
                    callBack && callBack(true)
                } else {
                    that._getTokenFromServer(callBack)
                }
            }
        });
    }

    _getTokenFromServer(callBack) {
        var that  = this;
        wx.login({
            success: function (res) {
                console.log(res);
                 // 发送请求验证 token
                http.post('api/token/applet_login', {code:res.code}).then(res => {
                    if (res.code === 1) {
                        if (res.data.token) {
                            console.log('Token 有效');
                            wx.setStorageSync('token', res.data.token)
                            wx.setStorageSync('token_time', res.time)
                            wx.setStorageSync('isLogin', 1)

                            http.post('api/user/info').then(ret => {
                                wx.setStorageSync('userInfo', ret.data);
                            })

                            callBack && callBack(res.data.token)
                        } else {
                            callBack && callBack(false);
                        }
                    }
                });
            }
        })
    }
}

export {Token};